package com.uenpay.im.service;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.IBinder;
import android.os.RemoteException;
import android.text.TextUtils;
import android.util.Log;

import com.qiyunxin.android.http.HttpInvokeResultCode;
import com.qiyunxin.android.http.net.HttpText;
import com.qiyunxin.android.http.utils.Utils;
import com.qyx.android.aidl.IPushService;
import com.qyx.android.callback.socket.IGetIpAndPortListener;
import com.qyx.android.callback.socket.IGetSocketIpAndPortListener;
import com.qyx.android.callback.socket.ILoginSocketListener;
import com.qyx.android.callback.socket.IReceiveNewMsgListener;
import com.qyx.android.message.ConnectionHandler;
import com.qyx.android.message.JsonToQyxMsg;
import com.qyx.android.message.PushServiceShareData;
import com.qyx.android.message.type.MsgContentType;
import com.qyx.android.message.type.MsgStatusType;
import com.qyx.android.protocol.BaseContentModel;
import com.qyx.android.protocol.QyxMsg;
import com.qyx.android.protocol.SendMsgCallBack;
import com.qyx.android.protocol.SessionModel;
import com.uenpay.im.BroadcastAction;
import com.uenpay.im.IMApplication;
import com.uenpay.im.ui.old.activity.group.GroupMangerHandler;
import com.uenpay.im.invokeitems.GetSocketInvokeItem;
import com.uenpay.im.invokeitems.OfflineMsgInvokeItem;
import com.uenpay.im.invokeitems.getunreadmsg.GetJsonUnreadMsg;

import org.json.JSONObject;

import java.util.ArrayList;

/**
 * 后台进程服务
 *
 * @author SL
 * @copyRight http://www.qiyunxin.com
 */
public class PushService extends Service {
    /**
     * 连接管理
     */
    private ConnectionHandler mConnectionHandler;
    /**
     * 消息处理
     */
    // private MessageHandle messageHandle;
    private boolean is_unread_msg_run = false;
    private boolean is_have_network = false;
    private QyxMessageUtils messageUtils = null;

    private IPushService.Stub mPushServiceImpl = new IPushService.Stub() {
        @Override
        public void regRecvMsgCallback(String cust_id, String token, String login_auth) throws RemoteException {
            if (PushServiceShareData.getInstance().getCustId() != null && !PushServiceShareData.getInstance().getCustId().equals(cust_id)) {
                IMApplication.getInstance().closeDbHelper();
            }

            PushServiceShareData.getInstance().setOldCustId(PushServiceShareData.getInstance().getCustId());
            /**
             * 设置用户登录的custId
             */
            PushServiceShareData.getInstance().setCustId(cust_id);
            /**
             * 设置用户登录的token
             */
            PushServiceShareData.getInstance().setToken(token);
            /**
             * 设置登录auth
             */
            PushServiceShareData.getInstance().setAuth(login_auth);
            /**
             * 打开数据库
             */
            IMApplication.getInstance().getDbHelper();
            /**
             * 将上次发送消息中的队列标志为失败
             */
            mConnectionHandler.updateAllMsgSendFail();
        }

        @Override
        public int sendMessage(BaseContentModel baseContentModel, SessionModel sessionModel, SendMsgCallBack sendMsgCallBack)
                throws RemoteException {

            // SendingMsg sendingMsg = new SendingMsg();
            // sendingMsg.msg = mQyxMsg;
            // /**
            // * 往消息队列中添加发送的消息
            // */
            // mConnectionHandler.addSendingMsgToArraylist(sendingMsg);
            if (messageUtils != null) {
                /**
                 * 发送消息
                 */
                // return mConnectionHandler.sendMessages(messageUtils
                // .QyxMsgToMsgBase(mQyxMsg));
                return mConnectionHandler.sendMessage(baseContentModel, sessionModel, sendMsgCallBack);
            }
            // mConnectionHandler.sendMessages(mQyxMsg);
            return 1;
        }

        @Override
        public boolean setLogout(boolean is_logout) throws RemoteException {
            /**
             * 退出登录
             */
            PushServiceShareData.getInstance().setIsLogout(is_logout);
            String cust_id = PushServiceShareData.getInstance().getCustId();
            String old_cust_id = PushServiceShareData.getInstance().getOldCustId();
            if (!is_logout) {
                if (!TextUtils.isEmpty(cust_id) && !cust_id.equals(old_cust_id)) {
                    PushServiceShareData.getInstance().setOldCustId(cust_id);
                    mConnectionHandler.reConnSocket();
                } else if (!mConnectionHandler.getConnectionStatus()) {
                    mConnectionHandler.reConnSocket();
                }
            } else {
                mConnectionHandler.stopAll();
            }
            return false;
        }

        @Override
        public boolean delSendingMessage(String msg_no) throws RemoteException {
            return true;
        }
    };

    /**
     */
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                boolean old_is_have_network = is_have_network;
                is_have_network = Utils.isNetworkConnected(IMApplication.getAppContext());
                if (is_have_network) {
                    if (!old_is_have_network && !PushServiceShareData.getInstance().getIsLogout()) {
                        mConnectionHandler.reConnSocket();
                    }
                }
            }
        }
    };

    @Override
    public IBinder onBind(Intent intent) {
        return mPushServiceImpl;
    }

    @Override
    public void onCreate() {
        PushServiceShareData.getInstance().setIsLogout(true);
        IntentFilter mFilter = new IntentFilter();
        mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(mReceiver, mFilter);
        messageUtils = new QyxMessageUtils();
        // messageHandle = new MessageHandle(messageUtils);
        mConnectionHandler = new ConnectionHandler(new ILoginSocketListener() {

            @Override
            public void LoginStatus(int status) {
                /** 解析登录状态 **/
                operLoginStatusMsg(status);
            }
        }, new IGetIpAndPortListener() {

            @Override
            public void getip(IGetSocketIpAndPortListener andPortListener) {
                getSocketIpAndPortThread(andPortListener);
                // andPortListener.onGetSocketIpAndPort("139.196.39.116",
                // 30000);
            }
        }, new IReceiveNewMsgListener() {

            @Override
            public void onGetMsg(QyxMsg qyxMsg, boolean is_new_group_msg) {
                Log.e("接收到消息", "" + qyxMsg.content_json + "|" + qyxMsg.msg_no);
                if (is_new_group_msg) {
                    GroupMangerHandler groupMangerHandler = new GroupMangerHandler();
                    groupMangerHandler.getGroupDetail(qyxMsg.sessionModel.getSessionId() + "", null);
                }
            }
        }, messageUtils);
        super.onCreate();
    }

    @Override
    public void onDestroy() {
        PushServiceShareData.getInstance().setIsLogout(true);
        unregisterReceiver(mReceiver);
        mConnectionHandler.stopAll();
        mConnectionHandler = null;
        System.gc();
        sendBroadcast(new Intent(BroadcastAction.RESTART_APP_ACTION));
        super.onDestroy();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, START_STICKY, startId);
    }

    /**
     * 解析socket登录状态
     *
     * @param status_code
     */
    private void operLoginStatusMsg(int status_code) {
        if (status_code == MsgStatusType.SEND_MSG_SUCCESS) {
            Intent intent = new Intent(BroadcastAction.ACTION_CONN_STAUTS);
            intent.putExtra("status_code", 100);
            sendBroadcast(intent);
            getUnreadMsg();
        } else if (status_code == MsgStatusType.SIGN_IN_OTHER_DEVICE) {
            Intent intent = new Intent(BroadcastAction.ACTION_AUTH_EXPIRES);
            sendBroadcast(intent);
            return;
        }
    }

    /**
     * 获取ip和port
     *
     * @param ipAndPortListener
     */
    private void getSocketIpAndPortThread(final IGetSocketIpAndPortListener ipAndPortListener) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                GetSocketInvokeItem item = new GetSocketInvokeItem();
                HttpText mHttpText = new HttpText(item);
                mHttpText.Start();
                GetSocketInvokeItem.GetSocketResult result = item.getOutput();
                String html = item.GetResponseBody();
                if (TextUtils.isEmpty(html)) {
                    ipAndPortListener.onGetSocketIpAndPort("", 0);
                } else {
                    if (result.status == HttpInvokeResultCode.RESULT_OK && !TextUtils.isEmpty(result.ip) && result.port != 0) {
                        if (ipAndPortListener != null) {
                            ipAndPortListener.onGetSocketIpAndPort(result.ip, result.port);
                        }
                    } else {
                        ipAndPortListener.onGetSocketIpAndPort("", 0);
                    }
                }
            }
        }).start();
    }

    /**
     * 获取离线消息
     */
    private void getUnreadMsg() {
        if (is_unread_msg_run) {
            return;
        }
        is_unread_msg_run = true;
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    GetJsonUnreadMsg item = new GetJsonUnreadMsg();
                    HttpText mHttpText = new HttpText(item);
                    mHttpText.Start();

                    GetJsonUnreadMsg.GetUnReadMsgResult result = item.getOutput();
                    String html = item.GetResponseBody();
                    if (!TextUtils.isEmpty(html)) {
                        int len = 0;

                        if (result != null && result.status == HttpInvokeResultCode.RESULT_OK) {
                            ArrayList<JSONObject> arr = result.messageJsons;

                            if (arr != null) {
                                len = arr.size();
                                ArrayList<QyxMsg> unreadMsgs = new ArrayList<QyxMsg>();
                                // StringBuffer un_reand_msg = new
                                // StringBuffer();
                                for (int i = 0; i < len; i++) {
                                    JSONObject msgJson = arr.get(i);
                                    /**
                                     * 序列化消息
                                     */
                                    QyxMsg msg = JsonToQyxMsg.serializeOffLineMsg(msgJson, messageUtils);
                                    unreadMsgs.add(msg);
                                    // if (i == len - 1) {
                                    // un_reand_msg.append(msg.msg_id);
                                    // //messageHandle.operRecvOffLineMsg(msg,true);
                                    // mConnectionHandler.operRecvOffLineMsg(msg,true);
                                    // } else {
                                    // un_reand_msg.append(msg.msg_id
                                    // + ",");
                                    // //messageHandle.operRecvOffLineMsg(msg,false);
                                    // mConnectionHandler.operRecvOffLineMsg(msg,false);
                                    // }

                                    if (msg.msg_content_type == MsgContentType.REQUEST_VIDEO_CHAT) {
                                        Intent intent = new Intent(BroadcastAction.ACTION_CANCEL_ADD_OFF_LINE_VIDEO_CHAT);
                                        intent.putExtra("message", msg);
                                        sendBroadcast(intent);
                                    } else if (msg.msg_content_type == MsgContentType.CANCEL_CALL_VIDEO_CHAT) {
                                        Intent intent = new Intent(BroadcastAction.ACTION_CANCEL_REMOVE_OFF_LINE_VIDEO_CHAT);
                                        intent.putExtra("msg_no", msg.content);
                                        sendBroadcast(intent);
                                    }
                                    // try {
                                    // Thread.sleep(100);
                                    // } catch (InterruptedException e) {
                                    // e.printStackTrace();
                                    // }
                                }
                                mConnectionHandler.operRecvOffLineMsg(unreadMsgs);
                                OfflineMsgInvokeItem item_ack = new OfflineMsgInvokeItem(result.ids);
                                new HttpText(item_ack).Start();
                            }
                        }

                        if (len == 0) {
                            Intent intent = new Intent(BroadcastAction.ACTION_CONN_STAUTS);
                            intent.putExtra("status_code", 200);
                            sendBroadcast(intent);
                            break;
                        }
                    }
                    // try {
                    // Thread.sleep(200);
                    // } catch (InterruptedException e) {
                    // e.printStackTrace();
                    // }
                }

                is_unread_msg_run = false;
            }
        }).start();
    }
}